//
//  WZPublishViewController.swift
//  weibo
//
//  Created by mac on 16/3/5.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import SnapKit
import AFNetworking
let holderString = "下雨天干什么"
class WZPublishViewController: UIViewController,UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    var constrain:Constraint?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.grayColor()
        setupNav()
        setTextView()
        setupToolBar()
        setupUI()
        
        //创建通知检测键盘
        NSNotificationCenter.defaultCenter().addObserver(self,selector:"changeToolBarFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        
        // 创建通知监听表情按钮的点击事件
        NSNotificationCenter.defaultCenter().addObserver(self,selector:"WriteEmotionToTextView:", name: KNotificationWriteEmotion, object: nil)
    }
    
    
    
    
    
    func changeToolBarFrame(info:NSNotification){
        
        if let userInfo = info.userInfo {
            
            
            let endFrame = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue
            let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSTimeInterval
            
            self.constrain?.uninstall()
            toolBar.snp_updateConstraints { (make) -> Void in
                self.constrain = make.bottom.equalTo(self.view.snp_bottom).offset(KUIScreenH == (endFrame?.origin.y)! ? 0:-(endFrame?.height)!).constraint
                
            }
            
            UIView.animateWithDuration(duration!, animations: { () -> Void in
                self.toolBar.layoutIfNeeded()
                }) { (_) -> Void in
            }
            
            
        }
        
        
        
    }
    
    
    private func  setupUI(){
        textView.addSubview(photoCollectionView)
        
        
        
        photoCollectionView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(textView.snp_center)
            make.width.equalTo(KUIScreenW - CGFloat(Kmargin))
            make.height.equalTo(KUIScreenW - CGFloat(Kmargin))
        }
        
        
    }
    
    //    MARK:设置nav
    private   func setupNav(){
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "sendSina")
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        
        //        设置nav中间的titleView
        let titleLable = UILabel(frame: CGRectMake(0,0,200,44))
        titleLable.textAlignment = .Center
        titleLable.numberOfLines = 0
        let str = "发布微博 \n\(WZUserViewModel.shareInstance.userModel?.screen_name ?? "")"
        let attributed = NSMutableAttributedString(string: str)
        
        attributed.setAttributes([NSFontAttributeName: UIFont.systemFontOfSize(15)], range: NSMakeRange(0, 4))
        attributed.setAttributes([NSFontAttributeName: UIFont.systemFontOfSize(13),NSForegroundColorAttributeName: UIColor.orangeColor()], range: NSMakeRange(4, str.characters.count - 4))
        
        titleLable.attributedText = attributed
        navigationItem.titleView = titleLable
        
        navigationItem.rightBarButtonItem?.enabled = false
    }
//    MARK:发送微博
    func sendSina(){
        var publishString:String = ""
        
        textView.attributedText.enumerateAttributesInRange(NSMakeRange(0, textView.attributedText.length), options: []) { (data:[String:AnyObject], range:NSRange, _) -> Void in
//            print(data)
            if let attachment = data["NSAttachment"] as? WZAttachment{
                
                let chs = attachment.emotion?.chs
                publishString += chs!
                
            }else{
                
                let str = (self.textView.text as NSString).substringWithRange(range)
                publishString += str
            }
            

            if let access_token = WZUserViewModel.shareInstance.userModel?.access_token{
                
                   let manager = WZHTTPClient.shareInstance
  //  access_token	true	string	采用OAuth授权方式为必填参数，OAuth授权后获得。
   //   status	true	string	要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。
                let paramter = ["access_token":access_token,"status":publishString]
                
     
                manager.loadRequest(.POST, URLString: "https://api.weibo.com/2/statuses/update.json", parameters: paramter, success: { (JSON) -> () in
                     print("发布微博成功")
                    }, faile: { (error) -> () in
                     print("发布微博失败")
                })
  
            }
            
            
        }
        
        
        
    }
    func dismiss(){
        self.dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    
    // MARK:   设置textView
    func setTextView(){
        
        view.addSubview(textView)
        textView.backgroundColor = UIColor(white: 0.95, alpha: 1)
        textView.holderString = holderString
        textView.font = UIFont.systemFontOfSize(15)
        textView.alwaysBounceHorizontal = false
        textView.alwaysBounceVertical = false
        textView.delegate = self
        //添加视图
        textView.alwaysBounceVertical = true
        textView.keyboardDismissMode = .OnDrag
        
    }
    // MARK:   设置toolBAR
    func setupToolBar(){
        //修改toolBar的背景颜色
        toolBar.backgroundColor = UIColor.lightGrayColor()
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "choosePicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var btnArray = [UIBarButtonItem]()
        for dict in itemSettings{
            //            _highlighted
            //            创建一个自定义的按钮
            let button = UIButton(type: UIButtonType.Custom)
            //            为按钮设置普通状态下的图片
            button.setImage(UIImage(named: dict["imageName"]!), forState: UIControlState.Normal)
            //            为按钮设置高亮状态图片
            button.setImage(UIImage(named: "\(dict["imageName"])_highlighted"), forState: UIControlState.Highlighted)
            //            MARK: button的大小一定要设置!!!!!!!
            button.sizeToFit()
            //            判读如果有点击事件则添加点击事件
            if let action = dict["action"]{
                button.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
            }
            //            将创建的按钮转化为UIBarButtonItem类型的
            let btnItem = UIBarButtonItem(customView: button)
            //                将创建的按钮添加到数组中
            btnArray.append(btnItem)
            
            //  每次添加一个按钮后创建一个弹簧添加到数组中
            btnArray.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
            
        }
        
        btnArray.removeLast()
        
        toolBar.items = btnArray
        toolBar.backgroundColor = UIColor.redColor()
        
        view.addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            self.constrain = make.bottom.equalTo(view.snp_bottom).constraint
            make.height.equalTo(44)
        }
        
    }
    //    MARK:选择图片的按钮点击
    func choosePicture(){
        
        
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
            let imagePick = UIImagePickerController()
            imagePick.delegate = self
            presentViewController(imagePick, animated: true, completion: { () -> Void in
                
            })
            
        }
        
    }
    //    MARK:选择表情的按钮点击
    func inputEmoticon(){
        
        textView.resignFirstResponder()
        
        if textView.inputView == nil{
            
            textView.inputView = emojiInputView
            
        }else{
            textView.inputView = nil
            
        }
        textView.becomeFirstResponder()
        
        
    }
    
    //    MARK:在textView上显示表情
    @objc private func WriteEmotionToTextView(info:NSNotification){
        let emotion = info.userInfo!["userInfo"] as! WZEmojiModel
        //        print(emotion)
        
        if let png = emotion.png{
            
            let beforAttributedText = NSMutableAttributedString(attributedString: textView.attributedText)
            
            //           1 创建一个附件
            let attachment = WZAttachment()
            //            把传过来的emotion给他
            attachment.emotion = emotion
            //            2设置图片
            
            let imagePath = "\(emotion.path!)/\(png)"
            attachment.image = UIImage(named: imagePath)
            //            3赋值给Attribute
            let attribute = NSAttributedString(attachment: attachment)
            
            //           拼接
            let range = textView.selectedRange
            beforAttributedText.insertAttributedString(attribute, atIndex: range.location)
            
            textView.attributedText = beforAttributedText
            //            赋值后修改光标的位置
            textView.selectedRange = NSMakeRange(range.location + 1, 0)

        }
        
//        emoji表情的显示
        if let emoji = emotion.emoji{
            
            let beforAttribute = NSMutableAttributedString(attributedString: textView.attributedText)
            let range = textView.selectedRange
            beforAttribute.replaceCharactersInRange(NSMakeRange(range.location, 0), withString: emoji)
            
            textView.attributedText = beforAttribute
  
            
        }
        
        
        
        
        
    }
    //        MARK:销毁通知
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self, name: KNotificationWriteEmotion, object: nil)
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardDidChangeFrameNotification, object: nil)
        NSNotificationCenter.defaultCenter().removeObserver(self, name: KNotificationWriteEmotion, object: nil)
        
    }
    
    
    //    MARK:懒加载
    lazy var textView: WZTextView = {
        let textView = WZTextView(frame: self.view.frame)
        
        return textView
    }()
    lazy var toolBar: UIToolbar = {
        let toolBar = UIToolbar()
        return toolBar
        
    }()
    lazy var photoCollectionView:WZPhotoView = {
        
        let photoCollectionView = WZPhotoView()
        //        MARK:避免循环饮用
        weak  var weakSelf = self
        photoCollectionView.callBack = {
            
            weakSelf?.choosePicture()
        }
        return photoCollectionView
    }()
    
    lazy var emojiInputView: WZEmojiInputView = {
        let emoji = WZEmojiInputView()
        emoji.frame = CGRectMake(0,0,KUIScreenW,216)
        emoji.backgroundColor = UIColor.greenColor()
        return emoji
        
    }()
    
    
    
    
}
//MARK: 设置textView的代理协议
extension WZPublishViewController{
    func textViewDidChange(textView: UITextView) {
        if textView.hasText(){
            self.textView.holderString = ""
        }else{
            self.textView.holderString = holderString
        }
        self.textView.setNeedsDisplay()
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
}
extension WZPublishViewController{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        self.photoCollectionView.addImageToImageList(image)
        
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
}